<?php

$GLOBALS['_DBG'] = 1;

include 'const.inc';
include 'Zend/Loader.php';

include 'Zend/Registry.php';
include 'Zend/Config.php';
include 'Zend/Controller/Front.php';
include 'Zend/Layout.php';
include 'Zend/Session.php';
include 'Zend/Cache.php';
include 'Zend/Cache/Core.php';
include 'Zend/Cache/Backend/Memcached.php';
include 'Zend/Db/Table.php';
include 'Zend/Db/Adapter/Pdo/Mysql.php';

require 'lib/SessionManager.php';
require 'lib/Global.php';

if ($GLOBALS['_DBG'] == 1){
	include_once 'Zend/Db/Profiler.php';
}

class Bootstrap
{
    public static $frontController = null;

    public static $root = '';

    public static $registry = null;

    public static function run()
    {
        self::prepare();
        $response = self::$frontController->dispatch();
        self::sendResponse($response);
        if ($GLOBALS['_DBG']==1)
        {
			self::renderDevel();
		}
    }

    public static function prepare()
    {
        self::setupEnvironment();
        Zend_Loader::registerAutoload();
        self::setupRegistry();
        self::setupConfiguration();
        self::setupFrontController();
        self::setupView();
        self::setupActionHelper();
        self::setupDatabase();
        self::setupSession();
		self::setupRouter();
		self::setupMemcache(); 		
		self::setupThrift();
    }

    public static function setupEnvironment()
    {
		$d=date("Ymd", time());
		$dbg=$d . "dbg";
		if (isset($_COOKIE['_DBG']))
		{
			if ($_COOKIE['_DBG']==$dbg)
			{
				$GLOBALS['_DBG']=1;
			}
		}
		if (isset($_GET['_DBG']))
		{
			if ($_GET['_DBG']==$dbg && $GLOBALS['_DBG']==0)
			{
				$GLOBALS['_DBG']=1;
				setcookie("_DBG", $dbg, time() + 1800, "/", TAMTAY_COOKIE_DOMAIN);  
			}
			else if ($GLOBALS['_DBG']==1 && $_GET['_DBG']!=$dbg)
			{
				$GLOBALS['_DBG']=0;
				setcookie("_DBG", $dbg, time() - 1800, "/", TAMTAY_COOKIE_DOMAIN);  
			}
		}       		
		ini_set('display_startup_errors', $GLOBALS['_DBG']==1);
        self::$root = dirname(dirname(__FILE__));
    }

    public static function setupFrontController()
    {
        self::$frontController = Zend_Controller_Front::getInstance();        
        self::$frontController->returnResponse(true);  
        self::$frontController->addModuleDirectory(APPLICATION_PATH . DS . 'modules');
    }

    public static function setupView()
    {
		Zend_Layout::startMvc(array("layoutPath" => APPLICATION_PATH . '/layouts/scripts', "layout" => "default"));
		$view = Zend_Layout::getMvcInstance()->getView();
		//$view->doctype('XHTML1_STRICT');
		$view->addHelperPath(APPLICATION_PATH  . '/views/helpers', 'Tamtay_View_Helper');
		$view->addHelperPath(APPLICATION_PATH  . '/modules/home/views/helpers', 'My_View_Helper');		
    }

    public static function sendResponse(Zend_Controller_Response_Http $response)
    {
        
        $response->sendResponse();
    }

    public static function setupRegistry()
    {
		self::$registry = new Zend_Registry(array(), ArrayObject::ARRAY_AS_PROPS);
		Zend_Registry::setInstance(self::$registry);
		
		//memcached stats
		self::$registry->cache_stats=array("cache_hit" => array(), "cache_miss" => array(), "cache_set" => array());
		
		//user
		$user=(object)null;
		$user->uid=0;
		$user->name="";
		$user->avatar="/themes/mytt_themes/images/nophoto.gif";
		self::$registry->user=$user;
		
		//variables
		self::$registry->variables=null;
    }

    public static function setupConfiguration()
    {
		$config = new Zend_Config(require APPLICATION_PATH . '/config/tamtay.php');
        self::$registry->configuration = $config;
    }

    public static function setupDatabase()
    {
        $config = self::$registry->configuration;
		$dbAdapters = array();
		
		//$master_db = Zend_Db::factory($config->master_db);
		$master_db = new Zend_Db_Adapter_Pdo_Mysql($config->master_db->params);
		self::$registry->master_db = $master_db;
		Zend_Db_Table::setDefaultAdapter($master_db);
		$master_db->getProfiler()->setEnabled($GLOBALS['_DBG']==1);		
		$master_db->setFetchMode(Zend_Db::FETCH_OBJ);
				
		foreach($config->slave_dbs as $key => $params)
		{
			//$slave_db=Zend_Db::factory($params);
			$slave_db=new Zend_Db_Adapter_Pdo_Mysql($params->params);
			$slave_db->getProfiler()->setEnabled($GLOBALS['_DBG']==1);
			$slave_db->setFetchMode(Zend_Db::FETCH_OBJ);
			$dbAdapters[$key]=$slave_db;			
		}
		self::$registry->slave_dbs=$dbAdapters;
    }
    
    public static function setupThrift()
    {
		$config = new Zend_Config(require APPLICATION_PATH . '/config/thrift.php');
		self::$registry->thrift=$config;
	}
    
    public static function setupActionHelper()
    {
		Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . '/helpers', 'Helper');
    }
    
    public static function setupRouter()
    {
		$controller = Zend_Controller_Front::getInstance();
		$router=$controller->getRouter();

    //router for event
    include 'config/event_home.php';
    include 'config/event_event.php';
    include 'config/event_member.php';
    include 'config/event_comment.php';
    include 'config/event_video.php';
    include 'config/event_photo.php';
    include 'config/event_music.php';
    include 'config/event_bookmark.php';
    include 'config/event_blog.php';
    include 'config/event_my.php';
    include 'config/event_browse.php';
    include 'config/event_city.php';
    include 'config/event_district.php';
    include 'config/event_admin.php'; 
    include 'config/event_test.php';

    /** Common Routes **/
    $router->addRoute(
            "user_login",
            new Zend_Controller_Router_Route(
                'user/login',    array(
                            'module' => 'default',
                            'controller' => 'user',
                            'action' => 'login'
                        )
                )
            );
	}
		
	
	public static function setupMemcache()
	{
		$config = self::$registry->configuration->memcached;
		$servers=$config->servers;
		$compression=$config->compression;
		$cfg=array("servers" => array(), "compression" => $compression);
		foreach($servers as $key => $params)
		{
			$cfg["servers"][]=array("host" => $params->host, "port" => $params->port, "persistent" =>  $params->persistent);
		}
		self::$registry->memcached=$cfg;    
		$frontendOptions=array(
				'cache_id_prefix' => 'beta_photo_',
				'lifetime' => 1200,
				'automatic_serialization' => true
				);
		$backendOptions=$cfg;
		$meta_cache = Zend_Cache::factory('Core',	'Memcached', $frontendOptions, $backendOptions);
		Zend_Db_Table_Abstract::setDefaultMetadataCache($meta_cache);
		//$meta_cache->clean(Zend_Cache::CLEANING_MODE_ALL);
		if (MEMCACHEDB_ENABLED)
		{
			$config = self::$registry->configuration->memcachedb;
			$servers=$config->servers;
			$compression=$config->compression;
			$cfg=array("servers" => array(), "compression" => $compression);
			foreach($servers as $key => $params)
			{
				$cfg["servers"][]=array("host" => $params->host, "port" => $params->port, "persistent" =>  $params->persistent);
			}
			self::$registry->memcachedb=$cfg;
		}
	}
	
	public static function setupSession()
	{
		$config = self::$registry->configuration;
		$session_db = Zend_Db::factory($config->session_db);
		$session_db->getProfiler()->setEnabled($GLOBALS['_DBG']==1);
		$session_db->setFetchMode(Zend_Db::FETCH_OBJ);
		self::$registry->session_db=$session_db;
		
		Zend_Session::setOptions(array(
						'gc_probability' => 1,
						'gc_divisor' => 5000
						));
		
		$sessionManager = new SessionManager();
		$sessionManager->db=$session_db;  
		Zend_Session::setSaveHandler($sessionManager);	    		
		Zend_Session::setOptions(array("cookie_domain" => TAMTAY_COOKIE_DOMAIN, "name" => TAMTAY_SESSION_NAME));
		if ($_SERVER['REQUEST_METHOD']=='POST')
		{
			if (isset($_POST[session_name()]))
			{
				$sid=$_POST[session_name()];
				$_COOKIE[session_name()]=$sid;
				Zend_Session::setId($sid);
			}
		}
		Zend_Session::start();
	}
	
	public static function renderDevel()
	{
		$profilers=array();
		
		$db=Zend_Registry::get("master_db");
		$profiler=$db->getProfiler();	
		$profilers["master_db"]=$profiler;		
		
		$db_adapters=Zend_Registry::get("slave_dbs");
		foreach($db_adapters as $key => $db)
		{
			$profiler=$db->getProfiler();	
			$profilers[$key]=$profiler;
		}
		$db=Zend_Registry::get("session_db");
		$profiler=$db->getProfiler();	
		$profilers["session_db"]=$profiler;
		
		$cache_stats=Zend_Registry::get("cache_stats");
		
		$view = new Zend_View(array('basePath' => APPLICATION_PATH . '/modules/default/views/'));
		$view->profilers = $profilers;
		$view->cache_stats=$cache_stats;
		echo $view->render('devel.phtml');
	}
}

